from flask import Flask, render_template, request, flash, send_from_directory, abort
from forms import MultiUploadForm
from config import Config
from werkzeug.utils import secure_filename
import os

app = Flask(__name__)
app.config.from_object(Config)


@app.route('/')
def hello_world():
    return render_template('index.html')


@app.route('/profile')
def profile():
    return render_template('profile.html')


@app.route('/show')
def show():
    files = os.listdir(app.config['UPLOAD_PATH'])
    return render_template('show.html', files=files)


@app.route('/multi-upload', methods=['GET', 'POST'])
def multi_upload():
    forms = MultiUploadForm()
    if request.method == 'POST':
        for photo in forms.photos.data:
            if photo != '':
                photo_filename = secure_filename(photo.filename)
                file_ext = os.path.splitext(photo_filename)[-1]
                if file_ext not in app.config['UPLOAD_EXTENSIONS']:
                    return '不合法的图片格式', 400
                photo.save(os.path.join(app.config['UPLOAD_PATH'], photo_filename))
                flash('图片：<%s>上传成功' % photo_filename)
    return render_template('upload.html', forms=forms)


@app.route('/uploads/<path:filename>')
def get_file(filename):
    return send_from_directory(app.config['UPLOAD_PATH'], filename)


@app.errorhandler(404)
def page_not_found(error):
    return render_template('404.html'), 404


if __name__ == '__main__':
    app.run()
